package com.deyuanyun.pic.settings.task;

import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.settings.service.base.BizMsgUserService;
import com.deyuanyun.pic.settings.service.msgtemplate.MsgQueue;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  消息推送任务，每30秒执行一次
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-08-26
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class PushMsgTask implements Job {

    private static final Logger LOGGER = LoggerFactory.getLogger(PushMsgTask.class);

    private MsgQueue msgQueue = MsgQueue.getInstance();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        executeOperator();
        if(msgQueue.size() == 0) { //没有消息推送的时候删除消息推送任务
            try {
                Scheduler scheduler = context.getScheduler();
                scheduler.deleteJob(context.getJobDetail().getKey());
            } catch (SchedulerException e) {
                LOGGER.error("删除消息推送定时任务异常", e);
            }
        }
    }

    /**
     * 执行消息推送
     */
    private void executeOperator() {
        MsgQueue.PushMsgOperator msgOperator = msgQueue.get();
        try {
            LOGGER.info(Thread.currentThread().getName() + "进来了.");
            LOGGER.info("现在队列中有：" + msgQueue.size() + "条记录.");
            if (msgOperator == null) //为空的时候不向下执行
                return;
            BizMsgUserService bizMsgUserService = SpringAppliction.getBean(BizMsgUserService.class);
            LOGGER.info("开始推送消息");
            bizMsgUserService.insertUserMsg(msgOperator);
            LOGGER.info("推送消息结束");
        } catch (Exception e) {
            LOGGER.error("推送消息异常，重新入队", e);
            //重新入队等待下一次的消息处理
            msgQueue.addOperator(msgOperator);
        }
    }
}
